summaryrefslogtreecommitdiff
path: root/app/[lng]/test/table-v2/page.tsx
blob: 65c0ee1dfb3a893f6bede63fcd3fd9e0e75986ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
"use client";

import * as React from "react";
import { PaginationState, SortingState, ColumnFiltersState, GroupingState } from "@tanstack/react-table";
import { ClientVirtualTable } from "@/components/client-table-v2/client-virtual-table";
import { TestProduct } from "@/db/schema/test-table-v2";
import { productColumns, orderColumns } from "./columns";
import { OrderWithDetails } from "./column-defs";
import { 
  getAllProducts, 
  getProductTableData, 
  getOrderTableData,
  getProductTableDataWithGrouping,
  GroupInfo,
} from "./actions";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ChevronDown, ChevronRight, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";

// ============================================================
// Reusable Loading Overlay Component
// ============================================================

function LoadingOverlay({ 
  isLoading, 
  children 
}: { 
  isLoading: boolean; 
  children: React.ReactNode 
}) {
  return (
    <div className="relative">
      {children}
      {isLoading && (
        <div className="absolute inset-0 z-50 flex items-center justify-center bg-background/60 backdrop-blur-[2px] transition-all duration-200">
          <div className="flex items-center gap-2 px-4 py-2 bg-background rounded-lg shadow-lg border">
            <Loader2 className="h-5 w-5 animate-spin text-primary" />
            <span className="text-sm text-muted-foreground">Loading...</span>
          </div>
        </div>
      )}
    </div>
  );
}

// ============================================================
// Pattern 1: Client-Side Table
// ============================================================

function ClientSideTable() {
  const [data, setData] = React.useState<TestProduct[]>([]);
  const [isLoading, setIsLoading] = React.useState(true);

  React.useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        const products = await getAllProducts();
        setData(products);
      } catch (error) {
        console.error("Failed to fetch products:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center gap-2">
          <CardTitle>Pattern 1: Client-Side</CardTitle>
          <Badge variant="outline">fetchMode=&quot;client&quot;</Badge>
        </div>
        <CardDescription>
          모든 데이터를 한 번에 받아와 클라이언트에서 필터링/정렬/페이지네이션/그룹핑 처리합니다.
          <br />
          <span className="text-muted-foreground">
            적합: 데이터 1000건 이하, 빠른 인터랙션 필요 시
          </span>
          <br />
          <span className="text-emerald-600 text-sm">
            ✅ 그룹핑: 헤더 우클릭 → Group by [Column]
          </span>
        </CardDescription>
      </CardHeader>
      <CardContent>
        <LoadingOverlay isLoading={isLoading}>
          <div className="h-[500px]">
            <ClientVirtualTable
              fetchMode="client"
              data={data}
              columns={productColumns}
              isLoading={false} // LoadingOverlay로 처리
              enablePagination
              enableGrouping
              height="100%"
              enableUserPreset={true}
              tableKey="test-table-v2-pattern1"
            />
          </div>
        </LoadingOverlay>
      </CardContent>
    </Card>
  );
}

// ============================================================
// Pattern 2: Factory Service (Server-Side)
// ============================================================

function FactoryServiceTable() {
  const [data, setData] = React.useState<TestProduct[]>([]);
  const [totalRows, setTotalRows] = React.useState(0);
  const [isLoading, setIsLoading] = React.useState(true);

  // Table state
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  });
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]);
  const [globalFilter, setGlobalFilter] = React.useState("");

  // Fetch data on state change
  React.useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        const result = await getProductTableData({
          pagination,
          sorting,
          columnFilters,
          globalFilter,
        });
        setData(result.data);
        setTotalRows(result.totalRows);
      } catch (error) {
        console.error("Failed to fetch products:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, [pagination, sorting, columnFilters, globalFilter]);

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center gap-2">
          <CardTitle>Pattern 2: Factory Service</CardTitle>
          <Badge variant="outline">fetchMode=&quot;server&quot;</Badge>
          <Badge variant="secondary">createTableService</Badge>
        </div>
        <CardDescription>
          <code>createTableService</code>로 서버 액션을 자동 생성합니다.
          <br />
          <span className="text-muted-foreground">
            적합: 단순 CRUD, 마스터 테이블 조회
          </span>
          <br />
          <span className="text-amber-600 text-sm">
            ⚠️ 그룹핑: 서버 모드에서는 별도 구현 필요 (Pattern 2-B 참고)
          </span>
        </CardDescription>
      </CardHeader>
      <CardContent>
        <LoadingOverlay isLoading={isLoading}>
          <div className="h-[500px]">
            <ClientVirtualTable
              fetchMode="server"
              data={data}
              rowCount={totalRows}
              columns={productColumns}
              isLoading={false}
              enablePagination
              enableGrouping={false}
              height="100%"
              pagination={pagination}
              onPaginationChange={setPagination}
              sorting={sorting}
              onSortingChange={setSorting}
              columnFilters={columnFilters}
              onColumnFiltersChange={setColumnFilters}
              globalFilter={globalFilter}
              onGlobalFilterChange={setGlobalFilter}
              enableUserPreset={true}
              tableKey="test-table-v2-pattern-2-A"
            />
          </div>
        </LoadingOverlay>
      </CardContent>
    </Card>
  );
}

// ============================================================
// Pattern 2-B: Server-Side Grouping (Context Menu 방식)
// ============================================================

function ServerGroupingTable() {
  const [grouping, setGrouping] = React.useState<GroupingState>([]);
  const [expandedGroups, setExpandedGroups] = React.useState<string[]>([]);
  const [groups, setGroups] = React.useState<GroupInfo[]>([]);
  const [flatData, setFlatData] = React.useState<TestProduct[]>([]);
  const [isGrouped, setIsGrouped] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(true);
  const [totalRows, setTotalRows] = React.useState(0);
  const [sorting, setSorting] = React.useState<SortingState>([]);

  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  });

  // 데이터 페칭
  React.useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        const result = await getProductTableDataWithGrouping(
          { pagination, grouping, sorting },
          expandedGroups
        );
        
        if ('groups' in result) {
          setGroups(result.groups);
          setIsGrouped(true);
          setFlatData([]);
        } else {
          setFlatData(result.data);
          setTotalRows(result.totalRows);
          setIsGrouped(false);
          setGroups([]);
        }
      } catch (error) {
        console.error("Failed to fetch:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, [pagination, grouping, sorting, expandedGroups]);

  // 그룹 토글
  const toggleGroup = (groupKey: string) => {
    setExpandedGroups(prev => 
      prev.includes(groupKey) 
        ? prev.filter(k => k !== groupKey)
        : [...prev, groupKey]
    );
  };

  // 그룹핑 상태 변경 핸들러 (Context Menu에서 호출됨)
  const handleGroupingChange = React.useCallback((updater: GroupingState | ((old: GroupingState) => GroupingState)) => {
    const newGrouping = typeof updater === 'function' ? updater(grouping) : updater;
    setGrouping(newGrouping);
    setExpandedGroups([]); // 그룹핑 변경 시 확장 상태 초기화
  }, [grouping]);

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center gap-2">
          <CardTitle>Pattern 2-B: Server-Side Grouping</CardTitle>
          <Badge variant="outline">fetchMode=&quot;server&quot;</Badge>
          <Badge className="bg-emerald-500">GROUP BY</Badge>
        </div>
        <CardDescription>
          서버에서 GROUP BY + 집계 쿼리로 그룹 정보를 조회합니다.
          <br />
          <span className="text-emerald-600 text-sm">
            ✅ 그룹핑: 헤더 우클릭 → Group by [Column] (category, status, isNew만 지원)
          </span>
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 현재 그룹핑 상태 표시 */}
        {grouping.length > 0 && (
          <div className="flex items-center gap-2 text-sm">
            <span className="text-muted-foreground">Grouped by:</span>
            {grouping.map((col) => (
              <Badge key={col} variant="secondary">
                {col}
                <button
                  className="ml-1 hover:text-destructive"
                  onClick={() => setGrouping([])}
                >
                  ×
                </button>
              </Badge>
            ))}
          </div>
        )}

        {/* Content with Loading Overlay */}
        <LoadingOverlay isLoading={isLoading}>
          <div className="border rounded-md min-h-[400px] max-h-[500px] overflow-auto">
            {isGrouped ? (
              // Grouped View - Custom Rendering
              <div className="divide-y">
                {groups.length === 0 ? (
                  <div className="flex items-center justify-center h-[400px] text-muted-foreground">
                    No data
                  </div>
                ) : (
                  groups.map((group) => (
                    <div key={group.groupKey}>
                      {/* Group Header */}
                      <button
                        className="w-full px-4 py-3 flex items-center gap-3 hover:bg-muted/50 transition-colors text-left"
                        onClick={() => toggleGroup(group.groupKey)}
                      >
                        {expandedGroups.includes(group.groupKey) ? (
                          <ChevronDown className="w-4 h-4" />
                        ) : (
                          <ChevronRight className="w-4 h-4" />
                        )}
                        <span className="font-medium">
                          {grouping[0]}: <Badge variant="outline">{String(group.groupValue)}</Badge>
                        </span>
                        <span className="text-muted-foreground text-sm">
                          ({group.count} items)
                        </span>
                      </button>
                      
                      {/* Expanded Rows */}
                      {expandedGroups.includes(group.groupKey) && group.rows && (
                        <div className="bg-muted/20 border-t">
                          <table className="w-full text-sm">
                            <thead>
                              <tr className="border-b bg-muted/30">
                                <th className="px-4 py-2 text-left">ID</th>
                                <th className="px-4 py-2 text-left">SKU</th>
                                <th className="px-4 py-2 text-left">Name</th>
                                <th className="px-4 py-2 text-left">Price</th>
                                <th className="px-4 py-2 text-left">Stock</th>
                              </tr>
                            </thead>
                            <tbody>
                              {group.rows.map((row) => (
                                <tr key={row.id} className="border-b hover:bg-muted/30">
                                  <td className="px-4 py-2">{row.id}</td>
                                  <td className="px-4 py-2 font-mono text-xs">{row.sku}</td>
                                  <td className="px-4 py-2">{row.name}</td>
                                  <td className="px-4 py-2">
                                    {new Intl.NumberFormat("en-US", {
                                      style: "currency",
                                      currency: "USD",
                                    }).format(parseFloat(row.price))}
                                  </td>
                                  <td className="px-4 py-2">{row.stock}</td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      )}
                    </div>
                  ))
                )}
              </div>
            ) : (
              // Normal Table View with Context Menu Grouping
              <ClientVirtualTable
                fetchMode="server"
                data={flatData}
                rowCount={totalRows}
                columns={productColumns}
                enablePagination
                enableGrouping // Context Menu에서 Group By 옵션 활성화
                height="400px"
                pagination={pagination}
                onPaginationChange={setPagination}
                sorting={sorting}
                onSortingChange={setSorting}
                // 그룹핑 상태 연결
                grouping={grouping}
                onGroupingChange={handleGroupingChange}
              />
            )}
          </div>
        </LoadingOverlay>
      </CardContent>
    </Card>
  );
}

// ============================================================
// Pattern 3: Custom Service (Server-Side with Joins)
// ============================================================

function CustomServiceTable() {
  const [data, setData] = React.useState<OrderWithDetails[]>([]);
  const [totalRows, setTotalRows] = React.useState(0);
  const [isLoading, setIsLoading] = React.useState(true);

  // Table state
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  });
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]);
  const [globalFilter, setGlobalFilter] = React.useState("");

  // Fetch data on state change
  React.useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        const result = await getOrderTableData({
          pagination,
          sorting,
          columnFilters,
          globalFilter,
        });
        setData(result.data);
        setTotalRows(result.totalRows);
      } catch (error) {
        console.error("Failed to fetch orders:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, [pagination, sorting, columnFilters, globalFilter]);

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center gap-2">
          <CardTitle>Pattern 3: Custom Service</CardTitle>
          <Badge variant="outline">fetchMode=&quot;server&quot;</Badge>
          <Badge variant="secondary">DrizzleTableAdapter</Badge>
        </div>
        <CardDescription>
          <code>DrizzleTableAdapter</code>를 도구로 사용하여 복잡한 조인 쿼리를 직접 작성합니다.
          <br />
          <span className="text-muted-foreground">
            적합: 여러 테이블 조인, 복잡한 비즈니스 로직
          </span>
          <br />
          <span className="text-amber-600 text-sm">
            ⚠️ 그룹핑: 가상 컬럼(조인 결과)은 서버 GROUP BY 불가
          </span>
        </CardDescription>
      </CardHeader>
      <CardContent>
        <LoadingOverlay isLoading={isLoading}>
          <div className="h-[500px]">
            <ClientVirtualTable
              fetchMode="server"
              data={data}
              rowCount={totalRows}
              columns={orderColumns}
              isLoading={false}
              enablePagination
              enableGrouping={false}
              height="100%"
              pagination={pagination}
              onPaginationChange={setPagination}
              sorting={sorting}
              onSortingChange={setSorting}
              columnFilters={columnFilters}
              onColumnFiltersChange={setColumnFilters}
              globalFilter={globalFilter}
              onGlobalFilterChange={setGlobalFilter}
            />
          </div>
        </LoadingOverlay>
      </CardContent>
    </Card>
  );
}

// ============================================================
// Main Page
// ============================================================

export default function TableV2TestPage() {
  return (
    <div className="container py-6 space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">
          ClientVirtualTable V2 - 데이터 페칭 패턴 테스트
        </h1>
        <p className="text-muted-foreground mt-2">
          GUIDE.md에 정의된 데이터 페칭 패턴과 그룹핑 처리 방법을 테스트합니다.
          <br />
          테스트 전 시딩이 필요합니다: <code className="bg-muted px-1 rounded">npx tsx db/seeds/test-table-v2.ts</code>
        </p>
      </div>

      <Tabs defaultValue="pattern1" className="space-y-4">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="pattern1">
            1. Client-Side
          </TabsTrigger>
          <TabsTrigger value="pattern2">
            2. Factory Service
          </TabsTrigger>
          <TabsTrigger value="pattern2b">
            2-B. Server Grouping
          </TabsTrigger>
          <TabsTrigger value="pattern3">
            3. Custom Service
          </TabsTrigger>
        </TabsList>

        <TabsContent value="pattern1">
          <ClientSideTable />
        </TabsContent>

        <TabsContent value="pattern2">
          <FactoryServiceTable />
        </TabsContent>

        <TabsContent value="pattern2b">
          <ServerGroupingTable />
        </TabsContent>

        <TabsContent value="pattern3">
          <CustomServiceTable />
        </TabsContent>
      </Tabs>

      {/* Summary Table */}
      <Card>
        <CardHeader>
          <CardTitle>패턴별 그룹핑 지원 현황</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b">
                  <th className="text-left py-2 px-4">패턴</th>
                  <th className="text-left py-2 px-4">그룹핑 방식</th>
                  <th className="text-left py-2 px-4">가상 컬럼 지원</th>
                  <th className="text-left py-2 px-4">비고</th>
                </tr>
              </thead>
              <tbody>
                <tr className="border-b">
                  <td className="py-2 px-4 font-medium">1. Client-Side</td>
                  <td className="py-2 px-4">
                    <Badge className="bg-emerald-500">TanStack Grouping</Badge>
                  </td>
                  <td className="py-2 px-4">
                    <Badge className="bg-emerald-500">✓ 지원</Badge>
                  </td>
                  <td className="py-2 px-4 text-muted-foreground">
                    메모리에서 처리, 전체 데이터 필요
                  </td>
                </tr>
                <tr className="border-b">
                  <td className="py-2 px-4 font-medium">2. Factory Service</td>
                  <td className="py-2 px-4">
                    <Badge variant="outline">미지원</Badge>
                  </td>
                  <td className="py-2 px-4">-</td>
                  <td className="py-2 px-4 text-muted-foreground">
                    별도 구현 필요 (2-B 참고)
                  </td>
                </tr>
                <tr className="border-b">
                  <td className="py-2 px-4 font-medium">2-B. Server Grouping</td>
                  <td className="py-2 px-4">
                    <Badge className="bg-blue-500">DB GROUP BY</Badge>
                  </td>
                  <td className="py-2 px-4">
                    <Badge variant="destructive">✗ 불가</Badge>
                  </td>
                  <td className="py-2 px-4 text-muted-foreground">
                    serverGroupable 컬럼만 가능
                  </td>
                </tr>
                <tr>
                  <td className="py-2 px-4 font-medium">3. Custom Service</td>
                  <td className="py-2 px-4">
                    <Badge variant="secondary">커스텀 구현</Badge>
                  </td>
                  <td className="py-2 px-4">
                    <Badge variant="secondary">선택적</Badge>
                  </td>
                  <td className="py-2 px-4 text-muted-foreground">
                    쿼리 설계에 따라 다름
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* Column Groupability Info */}
      <Card>
        <CardHeader>
          <CardTitle>컬럼별 서버 그룹핑 지원 여부</CardTitle>
          <CardDescription>
            <code>meta.serverGroupable</code> 플래그로 DB GROUP BY 가능 여부를 표시합니다.
            <br />
            헤더 우클릭 시 &quot;Group by [Column]&quot; 메뉴가 표시됩니다.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-2">
            {productColumns.map((col) => {
              if (!('accessorKey' in col)) return null;
              const meta = col.meta as { serverGroupable?: boolean } | undefined;
              const isGroupable = meta?.serverGroupable;
              return (
                <Badge
                  key={col.accessorKey as string}
                  variant={isGroupable ? "default" : "outline"}
                  className={isGroupable ? "bg-emerald-500" : ""}
                >
                  {col.accessorKey as string}
                  {isGroupable && " ✓"}
                </Badge>
              );
            })}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}